const cloud = require('@cloudbase/node-sdk')

// 初始化云开发实例
const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV
})

// 获取数据库引用
const db = app.database()
const collection = db.collection('industry_data')

/**
 * industry_data CRUD 云函数
 * @param {Object} event - 云函数参数
 * @param {Object} context - 云函数上下文
 */
exports.main = async (event, context) => {
    const { action, data } = event

    try {
        // 操作日志
        console.log('industry-data-crud 调用:', { action, data })

        switch (action) {
            case 'create':
                return await createIndustryData(data)
            case 'read':
                return await getIndustryData(data)
            case 'update':
                return await updateIndustryData(data)
            case 'delete':
                return await deleteIndustryData(data)
            case 'list':
                return await listIndustryData(data)
            default:
                throw new Error('无效的操作类型')
        }
    } catch (error) {
        console.error('industry-data-crud 错误:', error)
        return {
            code: -1,
            message: error.message,
            data: null
        }
    }
}

// 创建行业数据
async function createIndustryData(data) {
    const { industryName, industryIcon, positions, resumeTips, successCases, uuid, enable } = data

    if (!industryName) {
        throw new Error('行业名称为必填项')
    }

    const result = await collection.add({
        industryName,
        industryIcon: industryIcon || '',
        positions: positions || [],
        resumeTips: resumeTips || [],
        successCases: successCases || [],
        uuid: uuid || '',
        enable: enable !== false, // 默认为true，只有明确设置为false时才为false
        createdAt: new Date(),
        updatedAt: new Date()
    })

    return {
        code: 0,
        message: '创建成功',
        data: result
    }
}

// 获取单个行业数据
async function getIndustryData(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(_id).get()

    if (!result.data || result.data.length === 0) {
        throw new Error('行业数据不存在')
    }

    return {
        code: 0,
        message: '查询成功',
        data: result.data[0]
    }
}

// 更新行业数据
async function updateIndustryData(data) {
    const { _id, industryName, industryIcon, positions, resumeTips, successCases, uuid, enable } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const updateData = {
        updatedAt: new Date()
    }

    if (industryName) updateData.industryName = industryName
    if (industryIcon !== undefined) updateData.industryIcon = industryIcon
    if (positions) updateData.positions = positions
    if (resumeTips) updateData.resumeTips = resumeTips
    if (successCases) updateData.successCases = successCases
    if (uuid) updateData.uuid = uuid
    if (enable !== undefined) updateData.enable = enable

    const result = await collection.doc(_id).update(updateData)

    return {
        code: 0,
        message: '更新成功',
        data: result
    }
}

// 删除行业数据
async function deleteIndustryData(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(_id).remove()

    return {
        code: 0,
        message: '删除成功',
        data: result
    }
}

// 获取行业数据列表
async function listIndustryData(data) {
    const { page = 1, pageSize = 10, industryName, enable } = data

    // 构建查询条件
    let queryCondition = {}

    // 按行业名称模糊查询
    if (industryName) {
        queryCondition.industryName = db.RegExp({
            regexp: industryName,
            options: 'i',
        })
    }

    // 根据启用状态筛选
    if (enable !== undefined) {
        const cmd = db.command
        if (enable === true) {
            // 构建启用状态的查询条件：enable为true或字段不存在
            queryCondition = cmd.and([
                queryCondition,
                cmd.or([
                    { enable: true },
                    { enable: cmd.exists(false) }
                ])
            ])
        } else if (enable === false) {
            // 禁用状态：enable必须为false
            queryCondition.enable = false
        }
    }

    console.log('查询条件:', JSON.stringify(queryCondition))

    // 创建查询对象
    const query = collection.where(queryCondition)

    const result = await query
        .orderBy('createdAt', 'desc')
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()

    const countResult = await query.count()

    return {
        code: 0,
        message: '查询成功',
        data: {
            list: result.data,
            total: countResult.total,
            page,
            pageSize
        }
    }
}